import pandas as pd

# --- 1. 心输出量百分比数据 (第一张表) ---
cardiac_output_percentages = [
    {"Tissue": "Adipose", "Male (% cardiac output)": 5, "Female (% cardiac output)": 8.5},
    {"Tissue": "Bone", "Male (% cardiac output)": 5, "Female (% cardiac output)": 5},
    {"Tissue": "Brain", "Male (% cardiac output)": 12, "Female (% cardiac output)": 12},
    {"Tissue": "Stomach and Oesophagus", "Male (% cardiac output)": 1, "Female (% cardiac output)": 1},
    {"Tissue": "Small Intestine", "Male (% cardiac output)": 10, "Female (% cardiac output)": 11},
    {"Tissue": "Villi", "Male (% cardiac output)": 6, "Female (% cardiac output)": 6},
    {"Tissue": "Large Intestine", "Male (% cardiac output)": 4, "Female (% cardiac output)": 5},
    {"Tissue": "Heart", "Male (% cardiac output)": 4, "Female (% cardiac output)": 5},
    {"Tissue": "Kidney", "Male (% cardiac output)": 19, "Female (% cardiac output)": 17},
    {"Tissue": "Liver (Arterial)", "Male (% cardiac output)": 6.5, "Female (% cardiac output)": 6.5},
    {"Tissue": "Liver (Portal)", "Male (% cardiac output)": 19, "Female (% cardiac output)": 21.5},
    {"Tissue": "Lung", "Male (% cardiac output)": 100, "Female (% cardiac output)": 100},
    {"Tissue": "Muscle", "Male​ (% cardiac output)": 17, "Female (% cardiac output)": 12},
    {"Tissue": "Pancreas", "Male (% cardiac output)": 1, "Female (% cardiac output)": 1},
    {"Tissue": "Skin", "Male (% cardiac output)": 5, "Female (% cardiac output)": 5},
    {"Tissue": "Spleen", "Male (% cardiac output)": 2, "Female (% cardiac output)": 3},
    {"Tissue": "Rectum", "Male (% cardiac output)": 0.0185, "Female (% cardiac output)": 0.0185},
    {"Tissue": "Synovial Joint", "Male (% cardiac output)": 0.0336, "Female (% cardiac output)": 0.0336},
    {"Tissue": "Additional Organ", "Male (% cardiac output)": 0.65, "Female (% cardiac output)": 0.65},
    {"Tissue": "Lymph Nodes", "Male (% cardiac output)": 3.89, "Female (% cardiac output)": 3.89}
]

# --- 2. 淋巴流量数据 (第二张表) ---
lymph_flow_data = [
    {"Tissue": "Adipose", "Lymph Flow Rates (% total lymph flow)": 12.8, "Lymph Flow Rate (pop rep L/h)": 0.049799},
    {"Tissue": "Bone", "Lymph Flow Rates (% total lymph flow)": 0, "Lymph Flow Rate (pop rep L/h)": 0},
    {"Tissue": "Brain", "Lymph Flow Rates (% total lymph flow)": 1.05, "Lymph Flow Rate (pop rep L/h)": 0.0040851},
    {"Tissue": "Small Intestine", "Lymph Flow Rates (% total lymph flow)": 12, "Lymph Flow Rate (pop rep L/h)": 0.046686},
    {"Tissue": "Large Intestine", "Lymph Flow Rates (% total lymph flow)": None, "Lymph Flow Rate (pop rep L/h)": None}, # 使用 None 表示原始数据中的 '-'
    {"Tissue": "Heart", "Lymph Flow Rates (% total lymph flow)": 1, "Lymph Flow Rate (pop rep L/h)": 0.0038905},
    {"Tissue": "Kidney", "Lymph Flow Rates (% total lymph flow)": 8.5, "Lymph Flow Rate (pop rep L/h)": 0.03307},
    {"Tissue": "Liver (Arterial)", "Lymph Flow Rates (% total lymph flow)": 33, "Lymph Flow Rate (pop rep L/h)": 0.12839},
    {"Tissue": "Liver (Portal)", "Lymph Flow Rates (% total lymph flow)": None, "Lymph Flow Rate (pop rep L/h)": None},
    {"Tissue": "Lung", "Lymph Flow Rates (% total lymph flow)": 3, "Lymph Flow Rate (pop rep L/h)": 0.011672},
    {"Tissue": "Muscle", "Lymph Flow Rates (% total lymph flow)": 16, "Lymph Flow Rate (pop rep L/h)": 0.062249},
    {"Tissue": "Pancreas", "Lymph Flow Rates (% total lymph flow)": 0.3, "Lymph Flow Rate (pop rep L/h)": 0.0011672},
    {"Tissue": "Skin", "Lymph Flow Rates (% total lymph flow)": 7.3, "Lymph Flow Rate (pop rep L/h)": 0.028401},
    {"Tissue": "Spleen", "Lymph Flow Rates (% total lymph flow)": 1, "Lymph Flow Rate (pop rep L/h)": 0.0038905},
    {"Tissue": "Rectum", "Lymph Flow Rates (% total lymph flow)": None, "Lymph Flow Rate (pop rep L/h)": None},
    {"Tissue": "Synovium", "Lymph Flow Rates (% total lymph flow)": 0.546, "Lymph Flow Rate (pop rep L/h)": 0.0021242},
    {"Tissue": "Thyroid", "Lymph Flow Rates (% total lymph flow)": 0, "Lymph Flow Rate (pop rep L/h)": 0},
    {"Tissue": "Other", "Lymph Flow Rates (% total lymph flow)": 0.0038552, "Lymph Flow Rate (pop rep L/h)": 0.00038905}
]

# --- 3. 配置参数 ---
# 设定一个典型的成人静息总心输出量 (L/分钟)
TOTAL_CARDIAC_OUTPUT_L_PER_MIN = 5.0 # 您可以根据实际需要修改此值

# 设定一个总淋巴流量 (L/小时)。
# 这个值是根据数据中多数器官的百分比和其代表性流量反推得出的。
# 例如，Heart (1%) 和 Spleen (​1%) 均对应 0.0038905 L/h，因此总淋巴流量约为 0.0038905 / 0.01 = 0.38905 L/h。
TOTAL_LYMPH_FLOW_L_PER_HOUR = 0.38905

# --- 4. 转换为 Pandas DataFrame ---
df_cardiac = pd.DataFrame(cardiac_output_percentages)
df_lymph = pd.DataFrame(lymph_flow_data)

# --- 5. 计算器官血流量 (Cardiac Output) ---
print("=" * 60)
print("--- 器官血流量计算结果 ---")
print("=" * 60)
print(f"假设的总心输出量: {TOTAL_CARDIAC_OUTPUT_L_PER_MIN} L/分钟\n")

# 计算男性各个器官的血流量
df_cardiac['Male Blood Flow (L/min)'] = df_cardiac['Male (% cardiac output)'] / 100 * TOTAL_CARDIAC_OUTPUT_L_PER_MIN
# 计算女性各个器官的血流量
df_cardiac['Female Blood Flow (L/min)'] = df_cardiac['Female (% cardiac output)'] / 100 * TOTAL_CARDIAC_OUTPUT_L_PER_MIN

# 打印出主要结果列
output_cardiac_df = df_cardiac[['Tissue', 'Male Blood Flow (L/min)', 'Female Blood Flow (L/min)']]
print(output_cardiac_df.to_string(index=False, float_format="{:.4f}".format)) # 使用to_string()并设置index=False可以打印整个DataFrame而不截断

# 补充说明和注意事项 (心输出量部分)
print("\n--- 心输出量计算注意事项 ---")
print("1. '肺部 (Lung)' 的心输出量百分比为 100%，这意味着全部心输出量都会经过肺部，这与体循环中对其他器官的血流分配概念不同。")
print("2. '肝脏 (门静脉) (Liver (Portal))' 的血流百分比指的是流经门静脉的血流，这部分血流主要来源于胃肠道、脾脏和胰腺。")
print("   因此，如果您将所有器官（不包括肺部）的百分比直接相加，总和可能会超过 100%。")
print("   这是因为某些血流（如门静脉血流）在计入肝脏血流之前，已经作为其他器官（如小肠、大肠、脾脏等）的血流被计算过。")
print("   本脚本是严格按照您提供的原始百分比进行比例计算，没有对这种复杂的血流路径进行深入建模，也没有尝试强制总和为 100%。")

# 计算并打印各性别器官血流百分比的总和 (不包括肺部，以验证上述说明)
male_sum_percent_cardiac = df_cardiac[df_cardiac['Tissue'] != 'Lung']['Male (% cardiac output)'].sum()
female_sum_percent_cardiac = df_cardiac[df_cardiac['Tissue'] != 'Lung']['Female (% cardiac output)'].sum()
male_sum_flow_cardiac = df_cardiac[df_cardiac['Tissue'] != 'Lung']['Male Blood Flow (L/min)'].sum()
female_sum_flow_cardiac = df_cardiac[df_cardiac['Tissue'] != 'Lung']['Female Blood Flow (L/min)'].sum()

print(f"\n- 男性器官总和百分比 (不包括肺部): {male_sum_percent_cardiac:.2f}%")
print(f"- 女性器官总和百分比 (不包括肺部): {female_sum_percent_cardiac:.2f}%")
print(f"- 男性总血流 (L/min) (不包括肺部): {male_sum_flow_cardiac:.4f} L/min")
print(f"- 女性总血流 (L/min) (不包括肺部): {female_sum_flow_cardiac:.4f} L/min")

# --- 6. 计算器官淋巴流量 (Lymph Flow) ---
print("\n" + "=" * 60)
print("--- 器官淋巴流量速率计算结果 ---")
print("=" * 60)
print(f"假设的总淋巴流量: {TOTAL_LYMPH_FLOW_L_PER_HOUR} L/小时\n")

# 初始化计算结果列
df_lymph['Calculated Lymph Flow (L/h)'] = None

# 遍历每一行进行计算​
for index, row in df_lymph.iterrows():
    percentage = row['Lymph Flow Rates (% total lymph flow)']
    if pd.notna(percentage): # 检查百分比是否为有效数值（非None）
        df_lymph.loc[index, 'Calculated Lymph Flow (L/h)'] = TOTAL_LYMPH_FLOW_L_PER_HOUR * (percentage / 100)

# 计算计算值与提供值的差异 (如果提供值和计算值都存在)
df_lymph['Difference (Calculated - Provided)'] = None
for index, row in df_lymph.iterrows():
    calculated_value = row['Calculated Lymph Flow (L/h)']
    provided_value = row['Lymph Flow Rate (pop rep L/h)']
    # 确保 provided_value 是数值，并且不是None，因为原始数据中的None在导入时可能变成NaN
    if pd.notna(calculated_value) and pd.notna(provided_value):
        df_lymph.loc[index, 'Difference (Calculated - Provided)'] = calculated_value - provided_value

# 打印出相关结果列
# 使用 to_string() 避免截断，并设置 float_format 提高可读性
print(df_lymph[['Tissue', 'Lymph Flow Rates (% total lymph flow)', 'Lymph Flow Rate (pop rep L/h)', 'Calculated Lymph Flow (L/h)', 'Difference (Calculated - Provided)']].to_string(index=False, float_format="{:.8f}".format))

# 补充说明和注意事项 (淋巴流量部分)
print("\n--- 淋巴流量计算注意事项 ---")
print("1. 'Calculated Lymph Flow (L/h)' 是根据假设的总淋巴流量和各组织所占百分比计算得出的。")
print("2. 'Lymph Flow Rate (pop rep L/h)' 是您原始数据中提供的代表性淋巴流量。")
print("3. 'Difference (Calculated - Provided)' 列显示了计算值与原始提供值之间的差异。")
print("   - 您可以看到，对于大多数组织，计算值与原始提供值非常接近，这表明我们假设的总淋巴流量 (0.38905 L/h) 与您数据中多数器官的比例是一致的。")
print("   - 特别注意 'Other' 组织：其原始提供值 (0.00038905 L/h) 远大于根据其百分比计算得出的值 (约 0.00001501 L/h)。")
print("     这可能表明 'Other' 组织的百分比或其代表性流量值存在数据不一致，或者它指的是一个不同的总淋巴流量。")
print("4. 数据中标记为 '-' 的组织（如 Large Intestine, Liver (Portal), Rectum）由于缺乏百分比数据，因此无法计算其淋巴流量。")

# 统计总和以供参考
sum_of_percentages_lymph = df_lymph['Lymph Flow Rates (% total lymph flow)'].dropna().sum()
print(f"\n- 已提供百分比的器官的百分比总和: {sum_of_percentages_lymph:.4f}%")

sum_of_calculated_flows_lymph = df_lymph['Calculated Lymph Flow (L/h)'].dropna().sum()
print(f"- 根据 {TOTAL_LYMPH_FLOW_L_PER_HOUR} L/h 总流量计算的淋巴流量总和: {sum_of_calculated_flows_lymph:.8f} L/h")

sum_of_provided_flows_lymph = df_lymph['Lymph Flow Rate (pop rep L/h)'].dropna().sum()
print(f"- 原始数据中提供的代表性淋巴流量总和: {sum_of_provided_flows_lymph:.8f} L/h")

def generate_tissue_flow_rate_parameters_from_df(df):
    """
    批量生成组织流量参数，输入人口学DataFrame，输出每个人每个组织的心输出量和淋巴流量参数（带id），
    组织血流量用每个人自己的心输出量（Heart_Heart_cardiac_output），如无则使用默认值5.0 L/min。
    """
    results = []
    for idx, row in df.iterrows():
        person_id = row.get('id', idx)
        # 获取个体心输出量（L/min），优先使用心脏模块计算的值
        cardiac_output = row.get('Heart_Heart_cardiac_output', 5.0)
        # 组织血流量（L/min, L/h）
        sex = row.get('sex', 'Male')
        for organ in cardiac_output_percentages:
            organ_row = {'id': person_id, 'Tissue': organ.get('Tissue', 'Unknown')}
            # 取性别百分比
            if sex == 'Female':
                percent = organ.get('Female (% cardiac output)', 0)
            else:
                percent = organ.get('Male (% cardiac output)', 0)
            organ_row['Cardiac Output Percent'] = percent
            organ_row['Cardiac Output (L/min)'] = (
                cardiac_output * percent / 100
            )
            organ_row['Cardiac Output (L/h)'] = (
                organ_row['Cardiac Output (L/min)'] * 60
            )
            results.append(organ_row)
        # 淋巴流量（仍用原有均值）
        for organ in lymph_flow_data:
            organ_row = {'id': person_id, 'Tissue': organ.get('Tissue', 'Unknown')}
            for k, v in organ.items():
                if k == 'Tissue':
                    continue
                organ_row[k] = v
            results.append(organ_row)
    return pd.DataFrame(results)

def tissue_flow_rate_long_to_wide(df):
    """
    将组织流量长表（每个人每组织一行）转换为宽表（每个人一行），
    只输出三个参数：
    1. 各个器官相对心输出量的血流量百分比
    2. 各个器官的真实血流量
    3. 各个器官的真实淋巴流量
    """
    # 检查输入DataFrame是否为空
    if df.empty:
        return pd.DataFrame(columns=['id'])
    
    # 检查是否有'Tissue'列
    if 'Tissue' not in df.columns:
        return pd.DataFrame(columns=['id'])
    
    # 分离血流量和淋巴流量数据
    cardiac_tissues = [organ['Tissue'] for organ in cardiac_output_percentages]
    lymph_tissues = [organ['Tissue'] for organ in lymph_flow_data]
    
    # 只处理有心输出量百分比数据的组织
    cardiac_data = df[df['Tissue'].isin(cardiac_tissues)].copy()
    lymph_data = df[df['Tissue'].isin(lymph_tissues)].copy()
    
    # 检查并去除重复的(id, Tissue)组合
    if not cardiac_data.empty:
        cardiac_data = cardiac_data.drop_duplicates(subset=['id', 'Tissue'], keep='first')
    if not lymph_data.empty:
        lymph_data = lymph_data.drop_duplicates(subset=['id', 'Tissue'], keep='first')
    
    # 1. 处理血流量百分比数据
    if not cardiac_data.empty:
        cardiac_wide = cardiac_data.pivot(
            index='id', columns='Tissue', values='Cardiac Output Percent'
        )
        cardiac_wide.columns = [
            f"TissueFlow_{tissue}_bloodflow_percent"
            for tissue in cardiac_wide.columns
        ]
        cardiac_wide = cardiac_wide.reset_index()
    else:
        cardiac_wide = pd.DataFrame(columns=['id'])
    
    # 2. 处理真实血流量数据（L/h）
    if not cardiac_data.empty and 'Cardiac Output (L/h)' in cardiac_data.columns:
        blood_flow_wide = cardiac_data.pivot(
            index='id', columns='Tissue', values='Cardiac Output (L/h)'
        )
        blood_flow_wide.columns = [
            f"TissueFlow_{tissue}_bloodflow_Lh"
            for tissue in blood_flow_wide.columns
        ]
        blood_flow_wide = blood_flow_wide.reset_index()
        
        # 合并血流量百分比和真实血流量
        if not cardiac_wide.empty:
            cardiac_wide = pd.merge(cardiac_wide, blood_flow_wide, on='id', how='left')
        else:
            cardiac_wide = blood_flow_wide
    
    # 3. 处理真实淋巴流量数据
    if not lymph_data.empty:
        # 过滤掉Lymph Flow Rate为None的数据，但保留所有组织
        valid_lymph_data = lymph_data[lymph_data['Lymph Flow Rate (pop rep L/h)'].notna()].copy()
        
        if not valid_lymph_data.empty:
            lymph_wide = valid_lymph_data.pivot(
                index='id', columns='Tissue', values='Lymph Flow Rate (pop rep L/h)'
            )
            lymph_wide.columns = [
                f"TissueFlow_{tissue}_lymphflow_Lh"
                for tissue in lymph_wide.columns
            ]
            lymph_wide = lymph_wide.reset_index()
        else:
            lymph_wide = pd.DataFrame(columns=['id'])
    else:
        lymph_wide = pd.DataFrame(columns=['id'])
    
    # 合并所有数据
    if not cardiac_wide.empty and not lymph_wide.empty:
        result = pd.merge(cardiac_wide, lymph_wide, on='id', how='outer')
    elif not cardiac_wide.empty:
        result = cardiac_wide
    elif not lymph_wide.empty:
        result = lymph_wide
    else:
        result = pd.DataFrame(columns=['id'])
    
    return result
